package cn.mntool.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * describe: zookeeper客户端
 *
 * @author lianying
 * @date 2020/07/25
 */
public class HelloZookeeper {
    private static ZooKeeper zooKeeper;
    private static Stat stat=new Stat();
    public static void main(String [] args) throws IOException, InterruptedException, KeeperException {
        //zookeeper配置数据存放路径
        String path = "/username";
        //连接zookeeper并且注册一个默认的监听器
        MyCustomWatcher myCustomWatcher = new MyCustomWatcher();
        zooKeeper = new ZooKeeper("192.168.100.100:2181", 50000,
                myCustomWatcher);
        myCustomWatcher.setZooKeeper(zooKeeper);
        Stat exists = zooKeeper.exists(path, true);
        if(exists==null)
        {
            List<ACL> aclList=new ArrayList<>();
            ACL acl=new ACL();
            // scheme--world, auth, digest, host/ip
            acl.setId(new Id("world","anyone"));
            //权限
            acl.setPerms(ZooDefs.Perms.ALL);
            aclList.add(acl);
            zooKeeper.create(path,"lianying".getBytes(),aclList, CreateMode.PERSISTENT);
        }
        //创建完要监听
        byte[] data = zooKeeper.getData(path, true, stat);
        System.out.println(new String(data));
        //获取path目录节点的配置数据，并注册默认的监听器
        Thread.sleep(Integer.MAX_VALUE);
    }
}
